package com.lyf.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.alibaba.fastjson.JSON;
import com.lyf.DTO.UserLoginDTO;
import com.lyf.comon.ResponseResult;
import com.lyf.entity.Admin;
import com.lyf.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import static com.lyf.constant.RedisConstants.LOGIN_CHECK_CODE_KEY;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController{

    @Autowired
    private LoginService loginSercice;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/admin/login")
    public ResponseResult login(@RequestBody UserLoginDTO userLoginDTO ){
       return loginSercice.login(userLoginDTO);
    }

    @PostMapping("/user/login")
    public ResponseResult loginUser(@RequestBody UserLoginDTO userLoginDTO ){
        return loginSercice.loginUser(userLoginDTO);
    }

    @GetMapping("/loginOut")
    public ResponseResult logout(){
        return loginSercice.logout();
    }


    @GetMapping("/getCode/*")
    public ResponseResult getCode(HttpServletRequest request){
        //生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 50, 4, 50);
        //得到验证码
        String checkCode = lineCaptcha.getCode();
        System.out.println("生成的验证码："+checkCode);
        String key = LOGIN_CHECK_CODE_KEY;
        if (redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
            redisTemplate.opsForValue().set(key,checkCode);
        }else{
            redisTemplate.opsForValue().set(key,checkCode);
        }
//        //存储验证码到session域中
//        HttpSession session = request.getSession();
//        session.setAttribute("checkCode",checkCode);
//        //设置验证码过期时间
//        session.setMaxInactiveInterval(3000);
        //返回Base64编码的图片JSON字符串
        String imageBase64Data = lineCaptcha.getImageBase64Data();
        String msg = checkCode != null ? "验证码获取成功！" : "验证码获取失败！";
        return new ResponseResult(200,msg,imageBase64Data);
    }
    

}
